import logging


from flask import make_response, abort, current_app, request
from flask.json import jsonify

from info import redis_store, constants
from info.modules.passport import passport_blu
from info.utils.captcha.captcha import captcha


@passport_blu.route("/image_code", methods=['POST', 'GET'])
def get_image_code():
    """
    获取图片验证码
    :return:
    """
    # 1. 获取到当前的图片编号id
    code_id = request.args.get('code_id')

    # 2. 生成验证码
    name, text, image = captcha.generate_captcha()
    try:
        # 保存当前生成的图片验证码内容
        redis_store.setex('ImageCode_' + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return make_response(jsonify(errmsg="保存图片失败"))

    # 返回响应内容
    response = make_response(image)
    # 设置内容类型
    response.headers['Content-Type'] = 'image/jpg'
    return response
